package com.dingyh.shopwebbackground.controller;


import com.dingyh.shopwebbackground.entity.Commodity;
import com.dingyh.shopwebbackground.entity.Stock;
import com.dingyh.shopwebbackground.service.CommodityService;
import com.dingyh.shopwebbackground.service.StockService;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-20
 */
@RestController
@CrossOrigin
@RequestMapping("/stock")
public class StockController {

    @Autowired
    StockService stockService;

    @Autowired
    private CommodityService commodityService;

    private final static long HUNDRED_DAY = 8640000000L;

    @RequestMapping("getStockList")
    public CommonResult<Object> getStockList(String saleid,@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.offsetPage((pageIndex-1)*pageSize,pageSize);
        List<Stock> stocks = stockService.getStockList(saleid);
        if (stocks.isEmpty()){
            return new CommonResult(200,"",stocks);
        }else {
            long currTime = System.currentTimeMillis();//获取当前时间的毫秒数
            stocks.forEach(stock -> {
                String expireState = "0";
                int result = Long.compare(currTime, stock.getExdate());
                if (result == 1) {   //过期
                    expireState = "2";
                } else if (result == 0) {   //临期
                    expireState = "1";
                } else {
                    long timeCurrent = stock.getExdate() - currTime;
                    int current = Long.compare(timeCurrent, HUNDRED_DAY);
                    if (-1 == current) {
                        //临期
                        expireState = "1";
                    }
                }
//            long timeCurrent = currTime - TWENTY_DAY;
//            String expireState = currTime >= stock.getExdate() ? "2" :
//                    (Long.compare(timeCurrent, stock.getExdate()) != -1 && Long.compare(currTime,  stock.getExdate()) == -1  ? "1" : "0");
                stock.setExpireState(expireState);
                Commodity commodity = commodityService.getById(stock.getGoodsid());
                stock.setGoodsname(commodity.getTitle());
            });
            PageInfo<Stock> pageInfo = new PageInfo<>(stocks);
            return new CommonResult(200, "", pageInfo);
        }
    };

    /**
     * 入库
     * @param goodsid
     * @param saleid
     * @param flot
     * @param qty
     * @param exdate
     * @param pdate
     * @return
     */
    @RequestMapping("/addStocked")
    public  CommonResult<Object> addStocked(String goodsid,String saleid,String flot,Long qty,Long exdate,Long pdate){
        Commodity commoditys = commodityService.getById(goodsid);
        if (commoditys == null) {
            return new CommonResult<>(500,"该商品不存在！");
        }
        int countFlot = stockService.getByFlot(flot);
        if( countFlot > 0 ){
            return new CommonResult<>(500,"该批次已存在");
        }
        Commodity commodity = commodityService.selectGoods(goodsid);
        if( null == commodity ){
            return new CommonResult(500, "没找到该商品！", null);
        }
        Stock stock = Stock.builder()
                .id(UUIDUtil.generator())
                .goodsid(goodsid)
                .saleid(saleid)
                .qty(qty)
                .flot(flot)
                .timeadd(System.currentTimeMillis())
                .exdate(exdate)
                .pdate(pdate)
                .build();
        boolean result = stockService.save(stock);
        commodity.setStock(commodity.getStock().add(BigDecimal.valueOf(qty)));
        commodityService.updStock(commodity);
        if (result) {
            return new CommonResult(200, "提价成功！", null);
        } else {
            return new CommonResult(500, "提交失败！", null);
        }
    }

    @RequestMapping("/selectByGoodsid")
    public CommonResult<Object> selectByGoodsid(String goodsid){
        Map<String,Object> map = new HashMap<>();
        map.put("goodsid",goodsid);
        List<Stock> stocks = stockService.selectByGoodsId(map);
        long currTime = System.currentTimeMillis();
        stocks.forEach(stock -> {
            long twentyTime = stock.getExdate() - currTime;
            String expireState = Long.compare(twentyTime, HUNDRED_DAY)!= -1 ? "0" :
                    ( Long.compare(stock.getExdate(), currTime) == -1  ? "2" : "1");
            stock.setExpireState(expireState);
            Commodity commodity = commodityService.getById(stock.getGoodsid());
            stock.setGoodsname(commodity.getTitle() );
        });
        if(stocks== null|| !stocks.isEmpty()){
            return new CommonResult(200,"",stocks);
        }else{
            return new CommonResult(500,"该商品暂无入库单",null);
        }
    }
}

